package com.lbc.syn;

//  不安全的买票
//  线程不安全，有重复的票和负数
public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station, "AAA").start();
        new Thread(station, "BBB").start();
        new Thread(station, "CCC").start();

    }
}

class BuyTicket implements Runnable {

    //  票
    int ticketNums = 100;
    //  标志位
    boolean flag = true;

    @Override
    public void run() {
        //  买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //  synchronized  同步方法，锁的是this
    private synchronized void buy() throws InterruptedException {
        //  判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }

        //  模拟延时
        Thread.sleep(10);

        //  买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}